import logging
from typing import List

from src.config.settings import BOOTSTRAP_NODES
from src.globals.globals import GlobalManage
from src.handle.event_handler.handler_decorator import HandlerRegister
from src.log.logger import setup_logger
from src.model.event.events import DHTPingSendEvent, DHTBootstrapStart
from src.routing.routing_table import Node


@HandlerRegister.register
class DHTBootstrapHandle:
    """DHT引导节点处理器"""
    
    def __init__(self, global_manage: GlobalManage):
        """初始化处理器
        
        Args:
            global_manage: 全局管理器实例
        """
        self.logger: logging.Logger = setup_logger("dht.bootstrap")
        self.global_manage: GlobalManage = global_manage  
        
    @HandlerRegister.subscribe(DHTBootstrapStart)
    def handle_bootstrap_start(self, event: DHTBootstrapStart) -> None:
        """处理引导节点启动事件
        
        Args:
            event: 引导节点启动事件
        """
        self.logger.info("引导节点启动事件已处理")
        self.global_manage.schedule.every(10).seconds.do(lambda: self.send_ping(event.unique_id))


    def send_ping(self,unique_id:str):
        nodes:List[Node] = GlobalManage.get_instance().get_routing_table(unique_id).get_all_nodes()
        
        temps:List[Node] = []

        if len(nodes) < 5:
          temps.extend(BOOTSTRAP_NODES)
        else:
          temps.extend(nodes)
        
        self.logger.info(f"当前节点数量: {len(temps)}")
        
        for node in temps:
            self.global_manage.publish_event(DHTPingSendEvent(unique_id=unique_id,address=node))


    async def stop(self) -> None:
        """停止DHT引导节点"""
        self.logger.info("停止DHT引导节点")

            
            
        